package com.example.area.io.netty.bio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * BIO服务端
 * @author kancy
 * @date 2019/2/23 13:22
 */
@Slf4j
public class Server {

	public static final int N_THREADS = 10;
	private static final int DEFAULT_PORT = 7777;
	private static ServerSocket serverSocket;
	private static ExecutorService executorService;

	public static void main(String[] args) {
		try {
			start();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void start() throws IOException{
		start(DEFAULT_PORT);
	}

	public synchronized static void start(int port) throws IOException {
		initServer(port);
		accpectSocket();

	}

	private static void accpectSocket() {
		if(serverSocket == null) return;
		try {
			for (;;){
				Socket accept = serverSocket.accept();
				log.info("成功接受一个请求：" + accept.getInetAddress());
				processRequest(accept);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void processRequest(Socket socket) {
		ServerHandler serverHandler = new ServerHandler(socket);
		executorService.execute(serverHandler);
	}

	private static void initServer(int port) throws IOException {
		if(executorService == null){
			executorService = Executors.newFixedThreadPool(N_THREADS);
		}
		if(serverSocket == null){
			serverSocket = new ServerSocket(port);
			log.info("服务端已启动成功：{}", port);
		}
	}

}

